import React, { useEffect, useState, useCallback } from 'react';
import { Divider, Empty, Button, Spin } from 'antd';
import { connect } from 'dva';
import CustomForm from '@/components/customForm/CustomForm';
import { openNotificationWithIcon } from 'utils/comm';
import { post } from 'utils/fetch';
import _get from 'lodash/get';

const defaultOnCancel = () => {
  window.parent.postMessage({type: 'backFromApply'}, '*');
};
const containerStyle = {
  width: '100%',
  // height: '100%',
  display: 'flex',
  justifyContent: 'center',
  // alignItems: 'center',
  // background: '#fff',
};
const NewApply = (props) => {
  const [{ datas, hasForm, error }, setState] = useState({
    hasForm: undefined,
    error: false,
    datas: [],
  });

  const [loading, setLoading] = useState(false);
  const {
    location: {
      query: { processInstanceId = '', branchCode },
    },
    onCancel = defaultOnCancel,
  } = props;

  const loadData = useCallback(() => {
    setLoading(true)
    post('/flow-platform/monitor/task/showFormsByInstanceId', { processInstanceId, branchCode })
      .then(({ errCode, errMsg, datas: _datas }) => {
      if (errCode !== 0) {
        openNotificationWithIcon(
          'error',
          '',
          errMsg || '获取处理表单信息失败',
        );
        setState({ error: true, datas: [] });
      } else {
        setState({
          datas: _datas,
          error: false,
          hasForm: _datas && _datas.length > 0 && _datas.some((d) => {
            const properties = _get(d,'fields.properties', null );
            return properties && Object.keys(properties).length > 0;
          }),
        });
      }
      window.parent.postMessage({ type: 'height', data: document.documentElement.scrollHeight }, '*');
      })
      .finally(()=> setLoading(false));
  }, [processInstanceId]); 

  useEffect(loadData, []);

  if (error || hasForm === false) {
    return (
      <div style={containerStyle}>
        <Empty
          image={Empty.PRESENTED_IMAGE_SIMPLE}
          description={error ? '获取表单信息失败' : '当前暂无表单'}
        >
          { error ? (
            <Button
              type="primary"
              style={{marginRight: 12}}
              onClick={loadData}
            >
              {/* error ? '重新加载' : '发起申请' */}
              重新加载
            </Button>
            ) : null }
          <Button onClick={onCancel}>取消</Button>
        </Empty>
      </div>
    );
  }

  if (hasForm) {
    return (
      <div style={{ padding: 12 }}>
        { datas.map(({ taskId, fieldData, fields }, index) => (
          <>
            <CustomForm
              // title="发起申请"
              /*
              confirmLoading={startLoading}
              onOk={(values) => {
                handleFormSave(values);
              }}
              onCancel={onCancel}
              */
              key={taskId}
              formConfigData={fields}
              dataLoading={loading}
              emptyWord="当前无表单"
              // action="申请"
              withModal={false}
              editable={false}
              isView
              initialValues={fieldData}
            />
            { index < datas.length ? <Divider /> : null }
          </>
        ))}
      </div>
    );
  }

  return <div style={containerStyle}><Spin /></div>;

};

export default connect(
  ({ FlowExecution, loading }) => ({
    FlowExecutionStore: FlowExecution,
    loading,
  })
)(NewApply);